<?php
namespace app\api\controller;

use app\common\controller\BaseController;
use app\common\service\YiPayService;
use app\common\service\MembershipService;
use support\Request;
use support\Db;
use support\Log;

/**
 * 余额充值控制器
 */
class BalanceController extends BaseController
{
    /**
     * 创建余额充值订单
     */
    public function createRechargeOrder(Request $request)
    {
        $userId = $request->user->id ?? 0;
        $amount = $request->post('amount', 0);
        $paymentMethod = $request->post('payment_method', 'yipay');

        if (!$userId) {
            return json(['code' => 401, 'msg' => '用户未登录']);
        }

        if ($amount <= 0 || $amount > 10000) {
            return json(['code' => 400, 'msg' => '充值金额必须在0.01-10000元之间']);
        }

        // 生成订单号
        $orderNo = 'B' . date('YmdHis') . rand(1000, 9999);
        
        // 创建充值记录
        $rechargeData = [
            'user_id' => $userId,
            'order_no' => $orderNo,
            'amount' => $amount,
            'payment_method' => $paymentMethod,
            'payment_status' => 'pending',
            'created_at' => date('Y-m-d H:i:s')
        ];

        try {
            Db::beginTransaction();
            
            // 创建账单记录
            $billingId = Db::table('gf_billing_records')->insertGetId([
                'user_id' => $userId,
                'bill_type' => 'recharge',
                'bill_subtype' => 'balance',
                'amount' => $amount,
                'balance_before' => 0, // 将在支付成功后更新
                'balance_after' => 0,
                'description' => "余额充值 ¥{$amount}",
                'payment_method' => $paymentMethod,
                'status' => 'pending',
                'created_at' => date('Y-m-d H:i:s')
            ]);

            // 创建充值订单
            $orderId = Db::table('gf_membership_orders')->insertGetId([
                'user_id' => $userId,
                'plan_type' => 'balance_recharge',
                'order_no' => $orderNo,
                'amount' => $amount,
                'final_amount' => $amount,
                'months' => 0,
                'payment_method' => $paymentMethod,
                'payment_status' => 'pending',
                'created_at' => date('Y-m-d H:i:s')
            ]);

            // 更新账单记录的关联ID
            Db::table('gf_billing_records')->where('id', $billingId)->update([
                'related_id' => $orderId,
                'updated_at' => date('Y-m-d H:i:s')
            ]);

            Db::commit();

            // 调用支付服务创建支付订单
            $yiPayService = new YiPayService();
            $payResult = $yiPayService->createOrder($orderNo, $amount, '余额充值', $userId);

            if ($payResult['code'] === 200) {
                return json([
                    'code' => 200,
                    'msg' => '订单创建成功',
                    'data' => [
                        'order_no' => $orderNo,
                        'payment_url' => $payResult['data']['payment_url'],
                        'qrcode' => $payResult['data']['qrcode'] ?? ''
                    ]
                ]);
            } else {
                return json(['code' => 500, 'msg' => '支付订单创建失败']);
            }

        } catch (\Exception $e) {
            Db::rollBack();
            return json(['code' => 500, 'msg' => '订单创建失败：' . $e->getMessage()]);
        }
    }

    /**
     * 获取用户余额信息
     */
    public function getBalance(Request $request)
    {
        $userId = $request->user->id ?? 0;

        if (!$userId) {
            return json(['code' => 401, 'msg' => '用户未登录']);
        }

        $balance = Db::table('gf_user_balances')
            ->where('user_id', $userId)
            ->first();

        if (!$balance) {
            // 创建初始余额记录
            $balance = [
                'user_id' => $userId,
                'balance' => 0.00,
                'frozen_balance' => 0.00,
                'total_recharge' => 0.00,
                'total_consume' => 0.00,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ];
            Db::table('gf_user_balances')->insert($balance);
        }

        return json([
            'code' => 200,
            'data' => $balance
        ]);
    }

    /**
     * 获取余额变动记录
     */
    public function getBalanceRecords(Request $request)
    {
        $userId = $request->user->id ?? 0;
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 10);
        $type = $request->get('type', ''); // recharge, consumption, refund

        if (!$userId) {
            return json(['code' => 401, 'msg' => '用户未登录']);
        }

        $query = Db::table('gf_billing_records')
            ->where('user_id', $userId)
            ->where('bill_subtype', 'balance')
            ->orderBy('created_at', 'desc');

        if ($type) {
            $query->where('bill_type', $type);
        }

        $total = $query->count();
        $records = $query->offset(($page - 1) * $limit)->limit($limit)->get();

        return json([
            'code' => 200,
            'data' => [
                'total' => $total,
                'records' => $records,
                'page' => $page,
                'limit' => $limit
            ]
        ]);
    }

    /**
     * 余额支付（自动扣款）
     */
    public function balancePayment(Request $request)
    {
        $userId = $request->user->id ?? 0;
        $amount = $request->post('amount', 0);
        $description = $request->post('description', '');
        $relatedId = $request->post('related_id', 0);
        $relatedType = $request->post('related_type', ''); // membership_renew, service_fee

        if (!$userId) {
            return json(['code' => 401, 'msg' => '用户未登录']);
        }

        if ($amount <= 0) {
            return json(['code' => 400, 'msg' => '支付金额必须大于0']);
        }

        try {
            Db::beginTransaction();

            // 获取用户余额
            $balance = Db::table('gf_user_balances')
                ->where('user_id', $userId)
                ->lockForUpdate()
                ->first();

            if (!$balance || $balance->balance < $amount) {
                Db::rollBack();
                return json(['code' => 400, 'msg' => '余额不足']);
            }

            // 扣除余额
            $newBalance = $balance->balance - $amount;
            Db::table('gf_user_balances')
                ->where('user_id', $userId)
                ->update([
                    'balance' => $newBalance,
                    'total_consume' => $balance->total_consume + $amount,
                    'updated_at' => date('Y-m-d H:i:s')
                ]);

            // 创建消费记录
            Db::table('gf_billing_records')->insert([
                'user_id' => $userId,
                'bill_type' => 'consumption',
                'bill_subtype' => 'balance',
                'amount' => -$amount,
                'balance_before' => $balance->balance,
                'balance_after' => $newBalance,
                'related_id' => $relatedId,
                'description' => $description ?: "余额支付 ¥{$amount}",
                'payment_method' => 'balance',
                'status' => 'completed',
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ]);

            // 记录自动扣费记录（如果是会员续费）
            if ($relatedType === 'membership_renew') {
                Db::table('gf_auto_charge_records')->insert([
                    'user_id' => $userId,
                    'membership_id' => $relatedId,
                    'amount' => $amount,
                    'discount_rate' => 90, // 余额支付享受9折优惠
                    'final_amount' => $amount,
                    'charge_type' => 'membership_renew',
                    'status' => 'success',
                    'created_at' => date('Y-m-d H:i:s')
                ]);
            }

            Db::commit();

            // 记录用户操作日志
            MembershipService::logUserAction($userId, 'balance_payment', $relatedType, $relatedId, null, [
                'amount' => $amount,
                'balance_before' => $balance->balance,
                'balance_after' => $newBalance
            ]);

            return json([
                'code' => 200,
                'msg' => '余额支付成功',
                'data' => [
                    'balance' => $newBalance,
                    'amount' => $amount
                ]
            ]);

        } catch (\Exception $e) {
            Db::rollBack();
            return json(['code' => 500, 'msg' => '支付失败：' . $e->getMessage()]);
        }
    }

    /**
     * 获取系统配置的余额相关设置
     */
    public function getBalanceConfig()
    {
        $config = Db::table('gf_system_config')
            ->whereIn('config_key', [
                'balance_renew_discount',
                'min_balance_for_renew',
                'enable_balance_payment'
            ])
            ->where('is_active', 1)
            ->pluck('config_value', 'config_key')
            ->toArray();

        return json([
            'code' => 200,
            'data' => $config
        ]);
    }

    /**
     * 处理易支付回调
     */
    public function handleYiPayNotify(Request $request)
    {
        try {
            $params = $request->all();
            Log::info('YiPay notify received', $params);
            
            // 验证签名
            $yiPayService = new YiPayService();
            if (!$yiPayService->verifySign($params)) {
                Log::error('YiPay notify signature verification failed');
                return 'fail';
            }
            
            // 获取订单信息
            $orderNo = $params['out_trade_no'] ?? '';
            $tradeNo = $params['trade_no'] ?? '';
            $amount = $params['money'] ?? 0;
            $status = $params['trade_status'] ?? '';
            
            if (empty($orderNo)) {
                Log::error('YiPay notify: missing order number');
                return 'fail';
            }
            
            // 查找订单
            $order = Db::table('gf_membership_orders')
                ->where('order_no', $orderNo)
                ->first();
                
            if (!$order) {
                Log::error("YiPay notify: order not found: {$orderNo}");
                return 'fail';
            }
            
            // 检查订单状态
            if ($order->status === 'completed') {
                Log::info("YiPay notify: order already completed: {$orderNo}");
                return 'success';
            }
            
            // 处理支付成功
            if ($status === 'TRADE_SUCCESS') {
                Db::beginTransaction();
                try {
                    // 更新订单状态
                    Db::table('gf_membership_orders')
                        ->where('id', $order->id)
                        ->update([
                            'status' => 'completed',
                            'trade_no' => $tradeNo,
                            'paid_at' => date('Y-m-d H:i:s'),
                            'updated_at' => date('Y-m-d H:i:s')
                        ]);
                    
                    // 如果是余额充值订单
                    if ($order->order_type === 'balance_recharge') {
                        // 增加用户余额
                        $userBalance = Db::table('gf_user_balances')
                            ->where('user_id', $order->user_id)
                            ->first();
                            
                        if ($userBalance) {
                            Db::table('gf_user_balances')
                                ->where('user_id', $order->user_id)
                                ->increment('balance', $amount);
                        } else {
                            Db::table('gf_user_balances')
                                ->insert([
                                    'user_id' => $order->user_id,
                                    'balance' => $amount,
                                    'created_at' => date('Y-m-d H:i:s'),
                                    'updated_at' => date('Y-m-d H:i:s')
                                ]);
                        }
                        
                        // 记录余额变动
                        Db::table('gf_billing_records')->insert([
                            'user_id' => $order->user_id,
                            'order_id' => $order->id,
                            'bill_type' => 'recharge',
                            'bill_subtype' => 'balance',
                            'amount' => $amount,
                            'balance_after' => ($userBalance ? $userBalance->balance + $amount : $amount),
                            'description' => '余额充值',
                            'payment_method' => '易支付',
                            'status' => 'completed',
                            'created_at' => date('Y-m-d H:i:s'),
                            'updated_at' => date('Y-m-d H:i:s')
                        ]);
                    }
                    
                    Db::commit();
                    Log::info("YiPay notify: order processed successfully: {$orderNo}");
                    return 'success';
                    
                } catch (\Exception $e) {
                    Db::rollBack();
                    Log::error("YiPay notify: transaction failed: " . $e->getMessage());
                    return 'fail';
                }
            } else {
                // 支付失败或其他状态
                Db::table('gf_membership_orders')
                    ->where('id', $order->id)
                    ->update([
                        'status' => 'failed',
                        'trade_no' => $tradeNo,
                        'updated_at' => date('Y-m-d H:i:s')
                    ]);
                    
                Log::info("YiPay notify: payment failed for order: {$orderNo}");
                return 'success';
            }
            
        } catch (\Exception $e) {
            Log::error("YiPay notify error: " . $e->getMessage());
            return 'fail';
        }
    }
}